<template>
  <div>
    <el-form ref="form" :model="formData" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="公告标题:" prop="title">
            <el-input v-model="formData.title"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="上线时间:" prop="publishTime">
            <el-date-picker
              v-model="formData.publishTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              style="width: 100%"
              :picker-options="pickerOptions1">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="下线时间:" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              style="width: 100%"
              :picker-options="pickerOptions1">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="类型:">
            <el-select v-model="afficheType" placeholder="请选择" @change="afficheTypeChange">
              <el-option
                v-for="item in typeOptions"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发布位置:">
            <el-select v-model="formData.location" placeholder="必填">
              <el-option
                v-for="item in locationOptions"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="afficheType==='link'">
        <el-col :span="12">
          <el-input v-model="formData.link" placeholder="请输入链接"></el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="是否置顶:">
            <el-select v-model="formData.isUp" placeholder="必填">
              <el-option
                v-for="item in upOptions"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <p>公告内容:</p>
          <vue-ueditor ueditorPath="//cdn.cd121.com/ueditor/1.4.3.3/"
                       @ready="editorReadyHandler"
                       :ueditorConfig="editorConfig"/>
        </el-col>
      </el-row>
    </el-form>
    <div class="btn-group-wrapper top">
      <el-button type="primary" icon="upload" @click="releaseHandler">发布</el-button>
      <el-button type="primary" icon="document" @click="draftHandler">草稿</el-button>
    </div>
  </div>
</template>
<script>

  import { mapActions, mapGetters } from 'vuex'
  import moduleStore from './bll/store'
  import store from '../../store'
  (!store.state.sysAffiches) && store.registerModule('sysAffiches', moduleStore)

  import VueUeditor from 'vue-ueditor';
  import { forAfficheAdd as editorConfig } from '../../common/editor.config'
  import stringUtil from '../../common/stringUtil';
  import assignDeep from 'assign-deep';
  import dateUtil from '../../common/dateUtil';
  export default{
    data() {
      return {
        //Date
        pickerOptions1: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        rules: {
          publishTime: [
            {required: true, message: '请输入上线时间', trigger: 'blur'}
          ],
          title: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ]
        },
        upOptions: [
          {
            value: true,
            label: '是'
          }, {
            value: false,
            label: '否'
          }
        ],
        locationOptions: [
          {
            value: 'APP',
            label: 'APP'
          }, {
            value: 'PC',
            label: 'PC'
          }
        ],
        typeOptions: [
          {
            value: 'link',
            label: '上传文件(PDF/WORD)'
          }, {
            value: 'content',
            label: '自定义编辑'
          }
        ],
        afficheType: 'content',
        formData: {
          // id: '',
          title: '',
          content: '',
          link: '',
          isUp: false,
          publishTime: '',
          endTime: '',
          location: 'APP'
        },
        editorConfig: editorConfig,
        editor: null,
        editorCallback: null
      }
    },
    components: {VueUeditor},
    mounted() {
      let self = this;
      let pageModel = this.getAffichePageModel;
      if (pageModel === 'UPDATE') {
        this.formData = assignDeep({}, this.getEditingAffiche);
        if ((stringUtil.isEmpty(this.formData.content)) && !(stringUtil.isEmpty(this.formData.link))) {
          this.editorCallback = function (editor) {
            editor.setDisabled('fullscreen');
            self.afficheType = 'link';
          }
        }
      } else {
        this.formData.publishTime = (new Date()).getTime();
      }
    },
    computed: {
      ...mapGetters(['getAffichePageModel', 'getEditingAffiche'])
    },
    methods: {
      ...mapActions(['releaseAffiche', 'updateAffiche']),
      editorReadyHandler(editorInstance) {
        this.editor = editorInstance;
        if (this.getAffichePageModel === 'UPDATE') {
          let content = this.formData.content ? this.formData.content : '';
          this.editor.setContent(content);
        }
        this.editorCallback && this.editorCallback(this.editor);
      },
      afficheTypeChange() {
        if (this.afficheType === 'link') {
          this.editor.setDisabled('fullscreen');
        } else {
          this.editor.setEnabled();
        }
      },
      getEditorContentHandler() {
        if (this.editor) {
          this.formData.content = this.editor.getContent();
        }
      },
      resetHandler() {
        this.$refs.form.resetFields();
      },
      releaseHandler() {
        let self = this;
        let valid = true;
        let data = {};
        let formData = assignDeep({}, this.formData);
        formData.publishTime = dateUtil.dateToTimeString(formData.publishTime);
        formData.endTime = dateUtil.dateToTimeString(formData.endTime);
        //不传多余的信息
        data.title = formData.title;
        data.isUp = formData.isUp;
        data.publishTime = formData.publishTime;
        data.location = formData.location;
        formData.id && (data.id = formData.id);
        formData.endTime && (data.endTime = formData.endTime);
        if (this.afficheType === 'content') {
          this.getEditorContentHandler();
          data.content = this.formData.content;
        } else if (this.afficheType === 'link') {
          data.link = this.formData.link;
        }
        if ((stringUtil.isEmpty(data.location)) || (stringUtil.isEmpty(data.title)) || (stringUtil.isEmpty(data.isUp)) || (stringUtil.isEmpty(data.publishTime)) || ((stringUtil.isEmpty(data.content)) && stringUtil.isEmpty(data.link))) {
          valid = false;
        }
        if (valid) {
          //继续添加 或 返回列表
          self[self.getAffichePageModel === 'ADD' ? 'releaseAffiche' : 'updateAffiche'](data).then(() => {
            //self.disable();
            if (self.getAffichePageModel === 'ADD') {
              self.resetHandler();
              self.$message.success('添加公告成功!');
            } else {
              self.$message.success('修改公告成功!');
            }
            setTimeout(function () {
              self.$router.push('/affiche/index');
            }, 1000);
          })
        } else {
          this.$message({
            showClose: true,
            message: '请检查是否有未填项。(公告标题，发布位置，是否置顶，发布时间，内容(或文件)为必填项。)',
            type: 'error'
          });
          return false;
        }

      },
      draftHandler() {
        this.$message.warning('草稿功能暂未开放')
        //this.getEditorContentHandler();
        //TODO 如果是修改的状态下，保存为草稿的逻辑
      }
    }
  }
</script>
<style>

  .half-item {
    display: inline-block;
    width: 49.7%;
  }

  .block-item {
    margin-bottom: 20px;
  }

  .block-item p {
    font-size: 14px;
    color: #48576a;
    margin-top: 0;
  }
</style>
